package alipaylogic

import (
	"context"
	"errors"
	"github.com/go-pay/gopay"
	"github.com/gogap/logs"
	"log"
	"yundian/internel/app/dao/userdao"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper/userresp"
	"yundian/internel/pkg/alipayex"
)

type AlipayUserLogic struct {
	*AlipayBaseLogic
}

func NewAlipayUserLogic() (*AlipayUserLogic, error) {
	response := &AlipayUserLogic{}
	var info *AlipayBaseLogic
	var err error

	if info, err = newAlipayBaseLogic(); err != nil {
		return response, err
	}

	response.AlipayBaseLogic = info
	return response, nil
}

// SystemOauthToken 查询用户授权
func (logic *AlipayUserLogic) SystemOauthToken(authCode string) (*alipayex.SystemOauthTokenResponse, error) {
	body := make(gopay.BodyMap)
	body.Set("code", authCode)
	body.Set("grant_type", "authorization_code")

	aliRsp, err := logic.Client.SystemOauthToken(context.Background(), body)
	if err != nil {
		log.Println("SystemOauthToken-err", err.Error())
	}
	return aliRsp, err
}

// UserInfoShare 查询用户信息
func (logic *AlipayUserLogic) UserInfoShare(authCode string) (*alipayex.UserInfoShareResponse, error) {
	aliRsp, err := logic.Client.UserInfoShare(context.Background(), authCode)
	if err != nil {
		log.Println("UserInfoShare-err", err.Error())
	}
	return aliRsp, err
}

// XmAlipayLogin 小曼登录-支付宝
func (logic *AlipayUserLogic) XmAlipayLogin(param *request.ZfbUserLoginReq, userInfo *userresp.PlaceUserInfo) error {
	authInfo, err := logic.SystemOauthToken(param.AuthCode)
	if authInfo == nil || authInfo.Response == nil || authInfo.Response.UserId == "" {
		logs.Error("XmAlipayLogin->SystemOauthToken-err", authInfo, err)
		return errors.New("登录错误~001")
	}

	authUserInfo, err := logic.UserInfoShare(authInfo.Response.AccessToken)
	if authUserInfo == nil || authUserInfo.Response == nil || authUserInfo.Response.UserId == "" {
		logs.Error("XmAlipayLogin->UserInfoShare-err", authInfo, err)
		return errors.New("登录错误~002")
	}

	if userInfo.ZfbOpenid != "" && authUserInfo.Response.UserId != userInfo.ZfbOpenid {
		return errors.New("帐号绑定不一致～003")
	}
	userInfo.ZfbPhone = authUserInfo.Response.Mobile
	userInfo.ZfbOpenid = authUserInfo.Response.UserId
	if err = userdao.NewUserDao().UpdateUserZfbOpenidByUserId(userInfo).Err; err != nil {
		return errors.New("登录错误~004")
	}

	return nil
}
